# -*- coding: utf-8 -*-
import datetime

from date_help import date_help
from openerp import models, fields


class bc_contract_period(models.Model):
    _name = 'bc.contract.period'

    contract_detail_id = fields.Many2one('bc.contract.detail', ondelete='cascade')
    contract_id = fields.Many2one('bc.contract', related='contract_detail_id.contract_id', store=True)
    resource_id = fields.Many2one('bc.resource', related='contract_detail_id.resource_id', store=True)
    expenseitem_id = fields.Many2one('bc.expenseitem', related='contract_detail_id.expenseitem_id', store=True)
    startdate = fields.Date()
    enddate = fields.Date()
    decmoney = fields.Float()
    index = fields.Integer()

    def has_contract_id(self, contract_id):
        """
        是否存在合同ID
        """
        return self.search([('contract_id', '=', contract_id)]).exists()

    def create_vals(self, obj, index, startdate, enddate):
        """
        根据contract_detail_id的startdate, enddate,每次改变startdate,index,递归创建
        :param obj:
        :param index:
        :param startdate:
        :param enddate:
        :return:
        """
        if (startdate > enddate):
            return False
        else:
            _enddate = date_help.get_enddate(obj.unit2, obj.interval, startdate, enddate)
            _decmoney = date_help.get_moeny(obj.unit, obj.price, startdate.strftime("%Y-%m-%d"),
                                            _enddate.strftime("%Y-%m-%d"))

            vals = {'contract_detail_id': obj.id,
                    'index': index,
                    'startdate': startdate,
                    'enddate': _enddate,
                    'decmoney': _decmoney}
            self.create(vals)  # 创建数据

            startdate = _enddate + datetime.timedelta(days=1)
            index = index + 1

            return self.create_vals(obj, index, startdate, enddate)

    def get_period_one(self, contract_id):
        """
        获取第一期的数据
        """
        return self.search([('contract_id', '=', contract_id), ('index', '=', 1)])


    def get_period(self,contract_id,date):
        """
        根据时间获取到需要生成的数据
        :param contract_id:
        :param date:
        :return:
        """
        return self.search([('contract_id', '=', contract_id), ('index', '=', 1)])

